package com.huali.servlet;

import com.huali.dao.Login02;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {

    private static Login02 login02 = new Login02();


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //设置响应的编码格式
        response.setContentType("text/html;charset=UTF-8");
        List<Map<String, Object>> list = login02.login(username, Integer.parseInt(password));
        if (list.size() > 0) {
            response.getOutputStream().write("登录成功".getBytes());
            response.getOutputStream().write("登录失败，密码错误".getBytes());
        }
        response.getOutputStream().write("账号错误".getBytes());
//        User user = Login01Dao.executeSql(username);
//        if (user != null) {
//            if (user.getPassword().equals(password)) {
//                response.getOutputStream().write("登录成功".getBytes());
//            }
//            response.getOutputStream().write("登录失败，密码错误".getBytes());
//        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //alt + enter  .var
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //判断账号是否是123
        if ("123".equals(username)) {
            //判断密码是否是123
            if ("123".equals(password)) {
                System.out.println("登录成功");


                //filter
                //Cookie cookie = new Cookie("huali", "0322");
                //response.addCookie(cookie);

                HttpSession session = request.getSession();
                session.setAttribute("huali", "0328");


                //转发
                request.getRequestDispatcher("/successful.html").forward(request, response);
                //结束方法
                return;
            }
        }
        System.out.println("登录失败");
        //重定向
        response.sendRedirect("/failing.html");
    }
}
